package com.icinfo.cloud.provider.punish.fileoperation.service.impl;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.punish.fileoperation.service.IFileOperationService;
import com.icinfo.cloud.provider.punish.fileoperation.vo.PunishFileVisitVo;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URL;

/**
 * 【V1.12.8】描述：文件操作接口
 *
 * @Author zhengqiang
 * @Date 2023/10/26 10:54
 **/
@Slf4j
@Service
public class FileOperationServiceImpl extends MyBatisServiceSupport implements IFileOperationService {

    /**
     * 【V1.12.8】描述： 根据文件路径获取访问信息
     *
     * @return {@link Result< PunishFileVisitVo>}
     * @author: zhengqiang
     * @date: 2023/10/26
     * @param: fileUrl
     **/
    @Override
    public Result<PunishFileVisitVo> getFileVisitByFileUrl(String fileUrl) {
        if (StringUtils.isBlank(fileUrl)) {
            throw new BusinessException("未指定文书地址");
        }
        PunishFileVisitVo visitVo = new PunishFileVisitVo();
        String fileType = null;
        try {
            fileType = FileTypeUtil.getType(new URL(fileUrl).openStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (ObjectUtil.isEmpty(fileType)) {
            fileType = fileUrl.substring(fileUrl.lastIndexOf(".") + 1);
        }
        visitVo.setFileType(fileType);
        byte[] bytes = HttpUtil.createGet(fileUrl).execute().bodyBytes();
        visitVo.setFileByte(bytes);
        return Result.success(visitVo);
    }


}
